package com.lindroy.androidplayer.viewmodels

import androidx.lifecycle.*
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.lindroy.androidplayer.logic.model.CoinHistoryResp
import com.lindroy.androidplayer.logic.network.base.http.observePageState
import com.lindroy.androidplayer.logic.network.repository.Repository
import com.lindroy.androidplayer.utils.SingleLiveEvent
import com.lindroy.androidplayer.utils.mapItem
import com.lindroy.androidplayer.utils.mapSingle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

/**
 * @author Lin
 * @date 2022/2/11
 * @function 我的积分-ViewModel
 */
class MyCoinViewModel : PageViewModel() {

    private val _coinCountLiveData = SingleLiveEvent<String>()

    private val rankingClickAction = SingleLiveEvent<Unit>()

    val coinCountLiveData = _coinCountLiveData.mapSingle { it }

    val rankingClickLiveData = rankingClickAction.mapSingle {  }

    val coinHistoryListLiveData: Flow<PagingData<CoinHistoryViewModel>>
        get() = Repository.coinHistory.mapItem {
            CoinHistoryViewModel(
                it.coinCount,
                it.date,
                it.desc,
                it.id,
                it.reason,
                it.type,
                it.userId,
                it.userName
            )
        }.cachedIn(viewModelScope)

    fun getCoinInfo(owner: LifecycleOwner) {
        Repository.getMyCoinInfo().observePageState(owner) {
            onStart {
                _coinCountLiveData.postValue("--")
            }
            onSuccess {
                _coinCountLiveData.postValue(it.coinCount.toString())
            }
            onFailure {
                _coinCountLiveData.postValue("--")
            }
        }
    }

    fun onRakingClick(){
        rankingClickAction.postValue(Unit)
    }
}